using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
using Common;
using Common.Enum;
using Microsoft.Win32;
using SProject;
using SProject.Program;

namespace PCR.PCRControls
{
	public partial class PCRProgram : UserControl, IComponentConnector
	{
		private static string DefaultSectName = Utility.GetMessage("section");

		public ObservableCollection<ISection> Items = new ObservableCollection<ISection>();

		private bool Click;

		public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(PCRProgram), new PropertyMetadata(false, OnIsReadOnlyChanged));

		public static readonly DependencyProperty TypeProperty = DependencyProperty.Register("Type", typeof(EProjectType), typeof(PCRProgram), new UIPropertyMetadata(EProjectType.AQ));

		public static readonly DependencyProperty ProgramProperty = DependencyProperty.Register("Program", typeof(SProject.Program.PCRProgram), typeof(PCRProgram), new PropertyMetadata(null, OnProgramChanged));

		public double deltT;

		public bool IsReadOnly
		{
			get
			{
				return (bool)GetValue(IsReadOnlyProperty);
			}
			set
			{
				SetValue(IsReadOnlyProperty, value);
			}
		}

		public EProjectType Type
		{
			get
			{
				return (EProjectType)GetValue(TypeProperty);
			}
			set
			{
				SetValue(TypeProperty, value);
			}
		}

		public SProject.Program.PCRProgram Program
		{
			get
			{
				return (SProject.Program.PCRProgram)GetValue(ProgramProperty);
			}
			set
			{
				SetValue(ProgramProperty, value);
			}
		}

		public PCRProgram()
		{
			Items.CollectionChanged += Items_CollectionChanged;
			InitializeComponent();
			ClearData();
		}

		private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			UpdateSectionName();
		}

		private void UpdateSectionName()
		{
			for (int i = 0; i < Items.Count; i++)
			{
				if (!(Items[i] is Section))
				{
					continue;
				}
				Section section = Items[i] as Section;
				if (string.IsNullOrEmpty(section.SectName))
				{
					section.SectName = DefaultSectName + (i + 1);
				}
				else if (section.SectName != DefaultSectName && section.SectName.StartsWith(DefaultSectName))
				{
					int result = 0;
					if (int.TryParse(section.SectName.Substring(DefaultSectName.Length, section.SectName.Length - DefaultSectName.Length), out result))
					{
						section.SectName = DefaultSectName + (i + 1);
					}
				}
			}
		}

		public void Add(ESectionType type = ESectionType.Section, bool after = false)
		{
			ISection section = Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
			if (section == null)
			{
				return;
			}
			switch (type)
			{
			case ESectionType.Section:
			{
				Section section3 = new Section();
				int num = Items.IndexOf(section) + (after ? 1 : 0);
				if (num == 0 && Items[0] is PreHeatSection)
				{
					num = 1;
				}
				Items.Insert(num, section3);
				cItems.Children.Insert(num, section3);
				ChangLineBinding(section3);
				break;
			}
			case ESectionType.Step:
				if (section is Section)
				{
					Section section2 = section as Section;
					Step step = section2.Get();
					if (step != null)
					{
						section2.Add(after);
						ChangLineBinding(section2);
					}
				}
				break;
			case ESectionType.Fution:
			{
				Fution fution = new Fution();
				int index2 = Items.IndexOf(section) + (after ? 1 : 0);
				Items.Insert(index2, fution);
				cItems.Children.Insert(index2, fution);
				ChangLineBinding(fution);
				break;
			}
			case ESectionType.HRM:
			{
				HRM hRM = new HRM();
				int index = Items.IndexOf(section) + (after ? 1 : 0);
				Items.Insert(index, hRM);
				cItems.Children.Insert(index, hRM);
				ChangLineBinding(hRM);
				break;
			}
			case (ESectionType)3:
				break;
			}
		}

		public void AddLast(ESectionType type = ESectionType.Section)
		{
			Items.FirstOrDefault();
			switch (type)
			{
			case ESectionType.Step:
			{
				ISection section2 = Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
				if (section2 != null && section2 is Section)
				{
					Section section3 = section2 as Section;
					section3.AddLast();
					ChangLineBinding(section3);
				}
				break;
			}
			case ESectionType.Section:
			{
				Section section = new Section();
				Items.Add(section);
				cItems.Children.Add(section);
				ChangLineBinding(section);
				break;
			}
			case ESectionType.Fution:
			{
				Fution fution = new Fution();
				Items.Add(fution);
				cItems.Children.Add(fution);
				ChangLineBinding(fution);
				break;
			}
			case ESectionType.HRM:
			{
				HRM hRM = new HRM();
				Items.Add(hRM);
				cItems.Children.Add(hRM);
				ChangLineBinding(hRM);
				break;
			}
			case ESectionType.PreHeat:
			{
				PreHeatSection preHeatSection = new PreHeatSection();
				Items.Add(preHeatSection);
				cItems.Children.Add(preHeatSection);
				ChangLineBinding(preHeatSection);
				break;
			}
			case (ESectionType)3:
				break;
			}
		}

		private void ChangLineBinding(ISection item, int index = -1)
		{
			if (index > -1)
			{
				if (index < Items.Count())
				{
					ChangeCurrentBinding(Items[index]);
				}
			}
			else
			{
				ChangeCurrentBinding(item);
				ChangeNextBinding(item);
			}
		}

		private void ChangeCurrentBinding(ISection item)
		{
			int num = Items.IndexOf(item);
			if (num == 0)
			{
				if (item is Section)
				{
					(item as Section).Items[0].PriorTempt = 25.0;
				}
				else if (item is Fution)
				{
					(item as Fution).PriorTempt = 25.0;
				}
				else if (item is HRM)
				{
					(item as HRM).PriorTempt = 25.0;
				}
			}
			else if (num > 0)
			{
				if (item is Section)
				{
					(item as Section).Items.First().SetBinding(Step.PriorTemptProperty, CreatePriorBinding(Items[num - 1]));
				}
				else if (item is Fution)
				{
					(item as Fution).SetBinding(Fution.PriorTemptProperty, CreatePriorBinding(Items[num - 1]));
				}
				else if (item is HRM)
				{
					(item as HRM).SetBinding(HRM.PriorTemptProperty, CreatePriorBinding(Items[num - 1]));
				}
			}
		}

		private void ChangeNextBinding(ISection item)
		{
			int num = Items.IndexOf(item);
			if (num < Items.Count - 1)
			{
				Binding binding = CreatePriorBinding(item);
				ISection section = Items[num + 1];
				if (section is Section)
				{
					(section as Section).Items.First().SetBinding(Step.PriorTemptProperty, binding);
				}
				else if (section is Fution)
				{
					(section as Fution).SetBinding(Fution.PriorTemptProperty, binding);
				}
				else if (section is HRM)
				{
					(section as HRM).SetBinding(HRM.PriorTemptProperty, binding);
				}
			}
		}

		private Binding CreatePriorBinding(ISection item)
		{
			Binding binding = new Binding();
			if (item is Section)
			{
				binding.Path = new PropertyPath("Temperature");
				binding.Source = (item as Section).Items.Last();
			}
			else if (item is PreHeatSection)
			{
				binding.Path = new PropertyPath("Temperature");
				binding.Source = item;
			}
			else
			{
				binding.Path = new PropertyPath("EndTempt");
				binding.Source = item;
			}
			binding.Mode = BindingMode.OneWay;
			return binding;
		}

		public bool Remove()
		{
			bool flag = false;
			ISection section = Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
			if (section != null)
			{
				int index = Items.IndexOf(section);
				if (section is Section)
				{
					Section section2 = section as Section;
					Step step = section2.Get();
					if (step != null && (flag = section2.Remove()))
					{
						index = -1;
					}
				}
				if (!flag && Items.Count > 1)
				{
					Items.Remove(section);
					cItems.Children.Remove(section as UserControl);
					flag = true;
				}
				if (flag)
				{
					ChangLineBinding(section, index);
					SetSelectedType(null);
				}
			}
			return flag;
		}

		private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			Click = true;
		}

		private void Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			if (!Click)
			{
				return;
			}
			Click = false;
			SetSelectedType(null);
			ISection section = e.Source as ISection;
			if (section == null || !section.IsSelected)
			{
				return;
			}
			foreach (ISection item in Items)
			{
				if (item != section)
				{
					item.IsSelected = false;
				}
			}
			SetSelectedType(section);
		}

		private void SetSelectedType(ISection sec)
		{
		}

		private void MenuItem_Click(object sender, RoutedEventArgs e)
		{
			ISection section = Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
			if (section != null && section is Section)
			{
				Section section2 = section as Section;
				section2.EditProgram();
			}
		}

		private void MenuItem_Click_1(object sender, RoutedEventArgs e)
		{
			ISection section = Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
			if (section != null)
			{
				section.ScreenTest = true;
			}
		}

		private void MenuItem_Click_2(object sender, RoutedEventArgs e)
		{
			Add(ESectionType.Section, true);
		}

		private void MenuItem_Click_3(object sender, RoutedEventArgs e)
		{
			Add(ESectionType.Step, true);
		}

		private void MenuItem_Click_4(object sender, RoutedEventArgs e)
		{
			Remove();
		}

		private static void OnIsReadOnlyChanged(object sender, DependencyPropertyChangedEventArgs args)
		{
			PCRProgram pCRProgram = sender as PCRProgram;
			if (pCRProgram != null)
			{
				pCRProgram.RefreshReadOnly();
			}
		}

		private void RefreshReadOnly()
		{
			List<ISection> list = Items.Where((ISection s) => s.IsSelected = true).ToList();
			foreach (ISection item in list)
			{
				item.IsSelected = false;
			}
			cItems.IsEnabled = !IsReadOnly;
			if (IsReadOnly)
			{
				Items.CollectionChanged -= Items_CollectionChanged;
			}
			else
			{
				Items.CollectionChanged += Items_CollectionChanged;
			}
			foreach (ISection item2 in Items)
			{
				if (item2 is Section)
				{
					if (IsReadOnly)
					{
						((Section)item2).UnRegisterEvent();
					}
					else
					{
						((Section)item2).RegisterEvent();
					}
				}
			}
		}

		private static void OnProgramChanged(object sender, DependencyPropertyChangedEventArgs args)
		{
			PCRProgram pCRProgram = sender as PCRProgram;
			if (pCRProgram != null)
			{
				pCRProgram.InitData(args.NewValue as SProject.Program.PCRProgram);
			}
		}

		public SProject.Program.PCRProgram GetData()
		{
			SProject.Program.PCRProgram pCRProgram = new SProject.Program.PCRProgram();
			pCRProgram.DeltT = deltT;
			pCRProgram.Programs.Clear();
			pCRProgram.IsReadOnly = !cItems.IsEnabled;
			foreach (ISection item2 in Items)
			{
				if (item2 is PreHeatSection)
				{
					PreHeatSection preHeatSection = item2 as PreHeatSection;
					PreHeatSegment preHeatSegment = new PreHeatSegment();
					preHeatSegment.Temperature = preHeatSection.Temperature;
					preHeatSegment.IsUse = preHeatSection.IsUse;
					PreHeatSegment item = preHeatSegment;
					pCRProgram.Programs.Add(item);
				}
				else if (item2 is Section)
				{
					Section section = item2 as Section;
					Segment segment = new Segment();
					segment.Name = section.SectName;
					segment.Cycles = section.WhileNum;
					Segment segment2 = segment;
					foreach (Step item3 in section.Items)
					{
						segment2.Items.Add(new SProject.Program.Step
						{
							Name = item3.StepName,
							IsAdvProgram = item3.Program,
							IsTempVarUp = (item3.AddTempt == 0),
							IsTimeVarUp = (item3.AddSecond == 0),
							IsUseRamp = item3.Program1,
							Ramp = item3.TemptRate,
							Temperature = item3.Temperature,
							TempVarValue = item3.TemptChange,
							IsAcquisition = item3.ScreenTest,
							HoldMinute = item3.StayMinute,
							HoldSecond = item3.StaySecond,
							TimeVarValue = item3.TimeSecond,
							StartCycle = item3.WhileNum
						});
					}
					pCRProgram.Programs.Add(segment2);
				}
				else if (item2 is Fution)
				{
					Fution fution = item2 as Fution;
					pCRProgram.Programs.Add(new MeltingSegment
					{
						Name = fution.SectName,
						StartTemp = fution.StartTempt,
						EndTemp = fution.EndTempt,
						HoldTime = fution.StaySecond,
						Rate = ((fution.cType.SelectedIndex == 0) ? fution.TemptRate : fution.TestTempt),
						ScanMode = fution.Type,
						IsHRM = false,
						Interval = fution.TestTempt
					});
				}
				else if (item2 is HRM)
				{
					HRM hRM = item2 as HRM;
					pCRProgram.Programs.Add(new MeltingSegment
					{
						Name = hRM.SectName,
						StartTemp = hRM.StartTempt,
						EndTemp = hRM.EndTempt,
						HoldTime = hRM.StaySecond,
						Rate = ((hRM.cType.SelectedIndex == 0) ? hRM.TemptRate : hRM.TestTempt),
						ScanMode = hRM.Type,
						IsHRM = true,
						Interval = hRM.TestTempt
					});
				}
			}
			return pCRProgram;
		}

		public void InitData(SProject.Program.PCRProgram data)
		{
			ClearData();
			if (data == null)
			{
				return;
			}
			deltT = data.DeltT;
			ISection section = Items.FirstOrDefault();
			foreach (BaseSegment program in data.Programs)
			{
				if (program is PreHeatSegment)
				{
					PreHeatSegment preHeatSegment = program as PreHeatSegment;
					AddLast(ESectionType.PreHeat);
					PreHeatSection preHeatSection = Items.LastOrDefault() as PreHeatSection;
					preHeatSection.Temperature = preHeatSegment.Temperature;
					preHeatSection.IsUse = preHeatSegment.IsUse;
				}
				else if (program is Segment)
				{
					Segment segment = program as Segment;
					AddLast();
					Section section2 = Items.LastOrDefault() as Section;
					section2.SectName = segment.Name;
					section2.WhileNum = segment.Cycles;
					Step step = section2.Items.FirstOrDefault();
					foreach (SProject.Program.Step item in segment.Items)
					{
						section2.AddLast();
						Step step2 = section2.Items.LastOrDefault();
						step2.StayMinute = item.HoldMinute;
						step2.StaySecond = item.HoldSecond;
						step2.ScreenTest = item.IsAcquisition;
						step2.Program = item.IsAdvProgram;
						step2.AddTempt = ((!item.IsTempVarUp) ? 1 : 0);
						step2.AddSecond = ((!item.IsTimeVarUp) ? 1 : 0);
						step2.StepName = item.Name;
						step2.Program1 = item.IsUseRamp;
						step2.TemptRate = item.Ramp;
						step2.Temperature = item.Temperature;
						step2.TemptChange = item.TempVarValue;
						step2.TimeSecond = item.TimeVarValue;
						step2.WhileNum = item.StartCycle;
					}
					section2.Items.Remove(step);
					section2.cItems.Children.Remove(step);
					ChangLineBinding(section2);
				}
				else if (program is MeltingSegment)
				{
					MeltingSegment meltingSegment = program as MeltingSegment;
					if (meltingSegment.IsHRM)
					{
						AddLast(ESectionType.HRM);
						HRM hRM = Items.LastOrDefault() as HRM;
						hRM.EndTempt = meltingSegment.EndTemp;
						hRM.StaySecond = meltingSegment.HoldTime;
						hRM.SectName = meltingSegment.Name;
						hRM.TemptRate = meltingSegment.Rate;
						hRM.Type = meltingSegment.ScanMode;
						hRM.StartTempt = meltingSegment.StartTemp;
						hRM.TestTempt = meltingSegment.Interval;
					}
					else
					{
						AddLast(ESectionType.Fution);
						Fution fution = Items.LastOrDefault() as Fution;
						fution.EndTempt = meltingSegment.EndTemp;
						fution.StaySecond = meltingSegment.HoldTime;
						fution.SectName = meltingSegment.Name;
						fution.TemptRate = meltingSegment.Rate;
						fution.Type = meltingSegment.ScanMode;
						fution.StartTempt = meltingSegment.StartTemp;
						fution.TestTempt = meltingSegment.Interval;
					}
				}
			}
			Items.Remove(section);
			cItems.Children.Remove(section as UserControl);
			ChangLineBinding(Items.FirstOrDefault());
			if (IsReadOnly)
			{
				return;
			}
			cItems.IsEnabled = !data.IsReadOnly;
			if (Items.Count > 0)
			{
				if (Items[0] is Section)
				{
					((Section)Items[0]).Items[0].IsSelected = true;
				}
				Items[0].IsSelected = true;
			}
		}

		public void ClearData()
		{
			Items.Clear();
			cItems.Children.Clear();
		}

		public bool CanAddSection(bool before)
		{
			if (IsReadOnly || Items.Count >= 9)
			{
				return false;
			}
			ISection section = Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
			if (section == null)
			{
				return false;
			}
			if (before)
			{
				return !(section is PreHeatSection);
			}
			return true;
		}

		public bool CanAddStep()
		{
			if (IsReadOnly)
			{
				return false;
			}
			ISection section = Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
			if (section != null && section is Section && ((Section)section).Items.Count < 9)
			{
				return ((Section)section).Get() != null;
			}
			return false;
		}

		public bool CanAddMelting()
		{
			return Items.Where((ISection s) => s is Fution).Count() == 0;
		}

		public bool CanAddHRM()
		{
			return Items.Where((ISection s) => s is HRM).Count() == 0;
		}

		public bool CanDelete()
		{
			if (IsReadOnly)
			{
				return false;
			}
			ISection section = Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
			if (section == null || !(section is Section))
			{
				return false;
			}
			if (Items.Count > 1)
			{
				return true;
			}
			if (((Section)section).Items.Count > 1)
			{
				return ((Section)section).Get() != null;
			}
			return false;
		}

		public ISection GetSelected()
		{
			return Items.Where((ISection s) => s.IsSelected).FirstOrDefault();
		}

		private void SaveImage_Click(object sender, RoutedEventArgs e)
		{
			if (SaveAsImage())
			{
				MessageBox.Show(Utility.GetMessage("msg_saveimage_sussess"));
			}
		}

		public bool SaveAsImage()
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog();
			saveFileDialog.InitialDirectory = Utility.GetMyDocumentFolder();
			saveFileDialog.Filter = string.Format("{1}{0}|*.{1}|{2}{0}|*.{2}|{3}{0}|*.{3}", Utility.GetMessage("File"), "png", "jpg", "bmp");
			if (saveFileDialog.ShowDialog() == true)
			{
				switch (saveFileDialog.FilterIndex)
				{
				case 1:
					Utility.SaveAsImagePng(saveFileDialog.FileName, cItems);
					break;
				case 2:
					Utility.SaveAsImageJpg(saveFileDialog.FileName, cItems);
					break;
				case 3:
					Utility.SaveAsImagebmp(saveFileDialog.FileName, cItems);
					break;
				}
				return true;
			}
			return false;
		}

		public void AddCustomMenu(ContextMenu menu)
		{
			if (menu == null)
			{
				return;
			}
			if (base.ContextMenu != null && base.ContextMenu.Items.Count > 0)
			{
				menu.Items.Add(new Separator());
				for (int num = menu.Items.Count - 1; num >= 0; num--)
				{
					object insertItem = menu.Items[num];
					menu.Items.RemoveAt(num);
					base.ContextMenu.Items.Insert(0, insertItem);
				}
			}
			else
			{
				base.ContextMenu = menu;
			}
		}

		private void SavedefultPCRProgram_Click(object sender, RoutedEventArgs e)
		{
			SProject.Program.PCRProgram data = GetData();
			data.IsReadOnly = false;
			if (PCRProgramManage.GetInstance().SavePCRProgram(Type, data))
			{
				MessageBox.Show(Utility.GetMessage("save_as_defaultPro_success"));
			}
		}
	}
}
